package com.shengqi.xinnongren.common.base;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;

import com.shengqi.xinnongren.work.dialog.LoadingDialog;

/**
 * Created by xuyougen on 2018/4/17.
 */

public abstract class BaseMvpFragment<V extends BaseView, P extends BasePresenter<V>> extends BaseFragment {

    private Dialog mLoadingDialog;
    private P mPresenter;

    private boolean isDataLoaded = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mLoadingDialog == null)
            mLoadingDialog = createProgressDialog();
        mPresenter = createPresenter();
        mPresenter.attach((V) this);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();
        getLazyData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        getLazyData();
        onVisibilityChanged(isVisibleToUser);
    }

    private void getLazyData() {
        if (getUserVisibleHint() && getView() != null) {
            if (!isDataLoaded) {
                lazyLoadData();
                isDataLoaded = true;
            }
        }
    }

    protected abstract void lazyLoadData();

    protected void onVisibilityChanged(boolean isVisibleToUser) {
    }

    protected abstract void initView();

    protected abstract void initData();

    protected abstract P createPresenter();

    public P getPresenter() {
        return mPresenter;
    }

    protected Dialog createProgressDialog() {
        Dialog dialog = new LoadingDialog.Builder(getContext()).build();
        dialog.setCancelable(false);
        return dialog;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.detach();
    }

    public void showLoadingDialog() {
        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    public void hideLoadingDialog() {
        if (mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }
}
